﻿namespace CSharpHelpers.Timers
{
    public delegate void DelegateThreadingTimer();

    class TimerHelper
    {
        public System.Threading.Timer ThreadingTimer = null;

        public DelegateThreadingTimer DgThreadingTimer;

        /// <summary>
        /// 开始定时器
        /// 1.dueTime为0，立即执行
        /// 2.如果period为0或者-1，并且dueTime为正时，只执行一次
        /// </summary>
        /// <param name="dueTime"></param>
        /// <param name="period"></param>
        public void Start(int dueTime, int period)
        {
            if (ThreadingTimer == null)
            {
                ThreadingTimer = new System.Threading.Timer(Timer_Elapesed, null, dueTime, period);
            }
            else
            {
                ThreadingTimer.Change(dueTime, period);
            }
        }

        public void Timer_Elapesed(object sender)
        {
            DgThreadingTimer();
        }

        /// <summary>
        /// 停止定时器
        /// </summary>
        public void Stop()
        {
            if (ThreadingTimer != null)
            {
                ThreadingTimer.Dispose();
            }
        }
    }
}
